package com.kiln.juxingqs.ui

import android.view.View
import androidx.recyclerview.widget.DividerItemDecoration
import client.global.commlib.widget.EmptyLayout
import com.kiln.juxingqs.R
import com.kiln.juxingqs.adapter.ProfitAndLossAdapter
import com.kiln.juxingqs.api.bean.GetPpRet
import com.kiln.juxingqs.databinding.ActivityPpProfitandlossBinding
import com.kiln.juxingqs.ui.vm.PpProfitAndLossViewModel
import com.kiln.juxingqs.BaseMiddleActivity

class PpProfitAndLossActivity :
    BaseMiddleActivity<PpProfitAndLossViewModel, ActivityPpProfitandlossBinding>() {

    val adapter: ProfitAndLossAdapter by lazy {
        ProfitAndLossAdapter(this@PpProfitAndLossActivity)
    }

    override fun getLayout(): Int {
        return R.layout.activity_pp_profitandloss
    }

    override fun initViewModel(): PpProfitAndLossViewModel = createViewModel()

    override fun initView() {
        binding.event = this
        binding.vm = viewModel

        binding.emptyLayout.setOnClickListener {
            viewModel.pageOne.value = 0
            viewModel.holdOne()
        }
        binding.recyclerView.adapter = adapter
        val decoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
        val dividerDrawable = resources.getDrawable(R.drawable.drawable_divider)
        decoration.setDrawable(dividerDrawable)
        binding.recyclerView.addItemDecoration(decoration)

        binding.recyclerView.onLoadMore = {
            if (adapter.hasMoreState.value!! && !viewModel.isOneLoading.value!!) {
                viewModel.holdOne()
            }
        }
    }

    override fun observerUI() {
        viewModel.callOne.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    val list =
                        it.data?.deal_list as MutableList<GetPpRet.Deal?>?
                    if (viewModel.pageOne.value == 1) {
                        adapter.submitList(list)
                    } else
                        adapter.appendList(list)
                    if (list != null && list.size > 0) {
                        if (list.size < 20) {
                            adapter.hasMoreState.value = false
                        }
                        binding.emptyLayout.visibility = View.GONE
                    } else {
                        if (adapter.itemCount == 0)
                            binding.emptyLayout.errorType = EmptyLayout.NODATA
                        adapter.hasMoreState.value = false
                    }
                } else {
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                }
            }
        })
    }

    override fun onResume() {
        super.onResume()
        viewModel.pageOne.value = 0
        viewModel.holdOne()
    }
}